// index.js
// 获取应用实例
const app = getApp();
import http from '../../utils/http.js';
import util from '../../utils/util.js';
import {
  env
} from '../../utils/config.js'
import {
  GetStoreHomeApi
} from "../../utils/api.js"
import { businessWalletInfoApi } from '../../utils/api.js';
import { GetMemberInfoApi,GetMemberViewApi,GetMemberDataApi } from '../../utils/newApi.js';

Page({
  data: {
    backBtnTop: 0,
    navTop: 0,
    navHeight: 0, //导航高度
    windowHeight: 0, //窗口高度
    menuButtonObject: {},
    userInfo: {},
    id:'',
    isAdmin: null,
    merChantInfo: {
      isContract:true
    }, // 商家信息
    businessData:{},
  },
  backGo(){
    wx.navigateBack({
      delta: 1
    });
  },
  businessWalletInfo(){
    businessWalletInfoApi({id: this.data.id}).then(res=>{
    
    })
  },
  close(){
    this.setData({
      'merChantInfo.isContract':true
    })
  },
  jumpSeal(){
    console.log(env,"env")
    if(env=='release'){
      var weburl = 'https://p.xiuxian.xialoukeji.com/contract/?token='+wx.getStorageSync('accessToken')+'&id='+this.data.merChantInfo.id+'&name='+this.data.merChantInfo.name;
      wx.setStorageSync('webUrl',weburl);
    }else{
      var weburl = 'https://test.p.xiuxian.xialoukeji.com/contract/?token='+wx.getStorageSync('accessToken')+'&id='+this.data.merChantInfo.id+'&name='+this.data.merChantInfo.name;
      wx.setStorageSync('webUrl',weburl);
    }
  
    wx.navigateTo({
      url: '/pages/signature/signature',
    })
  },
  memberInfo(){
    GetMemberViewApi({id:this.data.id}).then(res=>{
      this.setData({
        merChantInfo: res.data
      })
    })
    GetMemberDataApi({storeId:this.data.id}).then(res=>{
      this.setData({
        businessData: res.data
      })
    })
  },
  onLoad(options) {
    console.log(2222,"222")
    let that = this
    console.log(options)
    that.setData({
      isAdmin : options.admin,
      id: options.id,
      navTop: app.globalData.navTop,
      navHeight: app.globalData.navHeight,
      navTop: app.globalData.navTop,
      menuButtonObject: app.globalData.menuButtonObject
    })
    console.log(that.data.isAdmin,"isAdmin")
    // that.getShopInfo()
    // that.memberInfo();
  },
  WeixinServer(){
    wx.openCustomerServiceChat({
      extInfo: {
        url:'https://work.weixin.qq.com/kf/' + "kfc11f5184d7762c658"
      },
      corpId: 'ww106853c8ad050781',
    })
  },
  onShow(){
    this.memberInfo();
    // this.getShopInfo()
    // this.businessWalletInfo()
  },

  onPullDownRefresh() {
    console.log('11')
    let that = this
    wx.showNavigationBarLoading()
    wx.showLoading()
    
    that.setData({
      merChantInfo: {}
    })
    that.getShopInfo()
    // that.businessWalletInfo()
    setTimeout(function () {
      // 取消标题栏进度条效果
      wx.hideNavigationBarLoading()
      wx.stopPullDownRefresh()
      wx.hideLoading()
    }, 1000)
  },

  quitAccount(){
    wx.clearStorage()
    wx.redirectTo({
      url: '/pages/login/login'
    })
  },

  jumpPage(e) {
    // wx.showToast({
    //   title: '功能暂未开放',
    //   icon: 'none',
    //   duration: 2000
    // })
    // return;
    const { page, type,child } = e.currentTarget.dataset
    if (page) {
      let path = '/pages/' + page + '/' + page;
      switch (page) {
        case 'memberManage':
          wx.navigateTo({
            url: path + '?id=' + this.data.id + '&admin=' + this.data.isAdmin,
          })
          break;
        case 'sales':
          wx.navigateTo({
            url: path + '?id=' + this.data.id + '&admin=' + this.data.isAdmin,
          })
          break;
        case 'storeManage':
            wx.navigateTo({
              url: `/pages/storeManage/${child}/${child}` + '?id=' + this.data.id + '&admin=' + this.data.isAdmin,
            })
            break;
        default:
          wx.navigateTo({
            url: `${path}?businessId=${this.data.id}${type ? `&type=${type}` : ''}&admin=${this.data.isAdmin}`
          })
          break;
        }
    } else {
      wx.showToast({
        title: '功能暂未开放',
        icon: 'none',
        duration: 2000
      })
    }
  },

  // WeixinServer() {
  //   wx.openCustomerServiceChat({
  //     extInfo: {
  //       url: 'https://work.weixin.qq.com/kfid/kfc2b6c8fe7f848fd26',
  //     },
  //     corpId: 'ww106853c8ad050781',
  //     fail(fa) {
  //       wx.showToast({
  //         title: fa.errMsg,
  //         icon:'none'
  //       })
  //     }
  //   })
  // },

  scanCodeMed() {
    let that = this
    wx.scanCode({
      onlyFromCamera: true,
      onlyFromCamera: ['qrCode'],
      success(code) {
        let result = decodeURIComponent(code.result)
        // 加上判断判断是否大于30秒
        console.log(result,"result")
        // let dataPar=JSON.parse(result)
        // let nowdate=Date.parse(new Date())
        // let timeDiff =Number(nowdate)-Number(dataPar.timestamp)
        // let formatTimeDiff = timeDiff/1000
        // if(formatTimeDiff>30){
        //      wx.showToast({title:'当前二维码已失效，请刷新再试试吧',icon:'none'})
        //      return;
        // }
        // console.log(formatTimeDiff,"111")
        if (result.indexOf('orderId') > 0) {
          result = JSON.parse(result)
          if (result.orderId && result.type) {
            let orderId = result.orderId;
            switch (result.type) {
              case 'booking':
                http.post('/api/store/v1/appointment/scan', {
                  businessId: that.data.merChantInfo.id,
                  id: orderId,
                  codeTimestamp:result.timestamp,
                }, {
                  'content-type': 'application/json;charset=utf-8'
                }).then(res => {
                  if (res.code === 200) {
                    wx.setStorageSync('orderInfo', res.data)
                    that.setData({
                      orderInfo: res.data
                    })
                    wx.navigateTo({
                      url: `/pages/result/result?orderId=${res.data.id}&status=${res.data.status}`
                    })
                  } else {
                    wx.showToast({
                      title: res.message,
                      icon: 'none',
                      duration: 2000
                    })
                    setTimeout(function () {
                      wx.navigateTo({
                        url: `/pages/failResult/failResult?reason=` + res.message
                      })
                    })
                  }
                })
                break;
              case 'goods':
                http.get('/api/order/v1/goods/vifiry/' + orderId, {
                  type: 1
                }).then(res => {
                  if (res.code === 200) {
                    wx.setStorageSync('orderInfo', res.data)
                    that.setData({
                      orderInfo: res.data
                    })
                    wx.navigateTo({
                      url: `/pages/goodsSuccess/goodsSuccess?id=${orderId}`
                    })
                  } else {
                    setTimeout(function () {
                      wx.navigateTo({
                        url: `/pages/goodsFail/goodsFail?reason=` + res.message
                      })
                    }, 1500)
                  }
                })
                break;
              case 'orderCode':
                 console.log("核销代金券")
                 wx.navigateTo({
                  url: `/pages/couponResult/couponResult?orderId=${orderId}&businessId=${this.data.id}`
                })
                break;
              case 'orderBuy':
                 console.log("核销买单")
                 wx.navigateTo({
                  url: `/pages/billResult/billResult?orderId=${orderId}&businessId=${that.data.merChantInfo.id}`
                })
                break;
            }
          } else {
            wx.navigateTo({
              url: `/pages/failResult/failResult`,
            })
          }
        } else {
          wx.navigateTo({
            url: `/pages/failResult/failResult`,
          })
        }

      }
    })
  },

  // 新核销方法
  verificationCode(){
    let that = this
    wx.scanCode({
      onlyFromCamera: true,
      onlyFromCamera: ['qrCode'],
      success(code) {
        let result = decodeURIComponent(code.result)
        console.log(result,"result")
        
        if (result.indexOf('orderId') > 0) {
            result = JSON.parse(result)
            let orderId = result.orderId;
            console.log(orderId,"orderId22222")
             wx.navigateTo({
                url: `/pages/couponResult/couponResult?orderId=${orderId}&storeId=${that.data.id}`
             })
        } else {
          wx.navigateTo({
            url: `/pages/failResult/failResult`,
          })
        }

      }
    })
  },

  getShopInfo() {
    let yesterday = new Date(new Date().getTime() - 1000 * 60 * 60 * 24)
    let year = yesterday.getFullYear()
    let month = Number(yesterday.getMonth() + 1) >= 10 ? Number(yesterday.getMonth() + 1) : '0' + Number(yesterday.getMonth() + 1)
    let day = Number(yesterday.getDate()) >= 10 ? Number(yesterday.getDate()) : '0' + Number(yesterday.getDate())
    yesterday = year + '-' + month + '-' + day
    if (app.globalData.accessToken) {
      let data={
        id: this.data.id,
        beginTime: yesterday + ' 00:00:00',
        endTime: yesterday + ' 23:59:59'
      }
      GetStoreHomeApi(data).then(res=>{
        console.log(res,"res")
        if (res.code === 200) {
          this.setData({
            merChantInfo: res.data,
            businessData:res.data.businessData
          })
          if(res.data.name.length>9){
            let objN=res.data.name.substring(0,9)
            this.setData({
             'merChantInfo.name':objN
            })
          }
          util.setStorageSync('storeInfo', res.data)
        }
      }).catch(err=>{})
      // http.post('/api/store/v1/store/home', {
      //   id: this.data.id,
      //   beginTime: yesterday + ' 00:00:00',
      //   endTime: yesterday + ' 23:59:59'
      // }).then(res => {
      //   if (res.code === 200) {
      //     this.setData({
      //       merChantInfo: res.data
      //     })
      //     util.setStorageSync('storeInfo', res.data)
      //   }
      // }).catch(() => {
      // })
    }
  },
  jumpPageBack(){
    wx.navigateBack({
      url: '/pages/index/index'
    })
  }
})